import React, { Component } from "react";

import {
  StyleSheet,
  View,
  Text,
  ScrollView,
  WebView
} from "react-native";

import { getStoryDetail } from "./../controllers/zhihuGetStories";

export default class ArticleScreen extends Component {

  static navigationOptions = {
    headerStyle: {
      "backgroundColor": "#00A2ED",
    }
  };

  constructor(props) {
    super(props);
    
    this.state = {
      htmlStr: ""
    }

    this.renderCount = 0;
  }

  // 知乎 api 回来的内容，需要重新组装下 body 内容
  getHtml(responseJson) {

    let { 
      body, 
      css, 
      js,
      title,
      image,
      image_source
    } = responseJson;

    // 将 body 中的部分内容替换掉
    let replaceStr = `
      <div class="img-wrap">
        <h1 class="headline-title">${title}</h1>
        <span class="img-source">图片:${image_source}</span>
        <img src="${image}" alt>
        <div class="img-mask"></div>
      </div>
    `;
    body = body.replace(/<div class="img-place-holder"><\/div>/, replaceStr);
    
    // 这里将 css 内容添加到 body 中
    let cssLinkArr = [], 
        jsScriptArr = [];

    css.unshift("https://daily.zhihu.com/css/share.css");
    css.map( link => {
      cssLinkArr.push(`<link rel="stylesheet" href="${link}">`);
    });

    js.map( script => {
      jsScriptArr.push(`<script src="${script}"></script>`);
    })

    return `<head><title>${title}</title>${cssLinkArr.join("")}</head>${body}${jsScriptArr.join("")}`;
  }

  // 跳转操作
  onNavigationChange() {
    console.log(arguments[0]);
  }

  componentDidMount() {

    const { id } = this.props.navigation.state.params;

    getStoryDetail(id).then( responseJson => {

        body = this.getHtml(responseJson);
        this.setState({ htmlStr: body });
      })
  }

  render() {

    console.log(this.renderCount++);

    let source = {
      html: this.state.htmlStr,
      headers: {
        "charset": "utf-8"
      }
    }

    return (

      <WebView
        style = { styles.container }
        source = { source }
        scalesPageToFit = { true }
        onNavigationStateChange = { this.onNavigationChange }
        startInLoadingState = { true }
      />
    );
  }
}

const styles = StyleSheet.create({

  container: {
    flex: 1
  }
});